﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using OptimumInfra.Models;
using OptimumInfra.ViewData;
using System.Collections.Specialized;


namespace OptimumInfra.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        private CustomerRepository repo = new CustomerRepository();

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email,model.PhoneNumber);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    Roles.AddUserToRole(model.UserName, "customer");
                    Customer c = new Customer();
                    c.Email = model.Email;
                    c.PhoneNumber = model.PhoneNumber;
                    c.UserName = model.UserName;
                    c.Address = model.Address;
                    this.repo.CreateCustomer(c);
                    TempData["info"] = "Your register has been succesful";
                    return RedirectToAction("Profile", "Account");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form

            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        public ActionResult CreateEmployee()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }
        [HttpPost]
        public ActionResult CreateEmployee(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email, model.PhoneNumber);

                if (createStatus == MembershipCreateStatus.Success)
                {
                   // FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    Roles.AddUserToRole(model.UserName, model.RoleName);
                    Customer c = new Customer();
                    c.Email = model.Email;
                    c.PhoneNumber = model.PhoneNumber;
                    c.UserName = model.UserName;
                    c.Address = model.Address;
                    this.repo.CreateCustomer(c);
                    TempData["info"] = "Create new employee was succesfull";
                    return RedirectToAction("Manage", "Account");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form

            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        [Authorize(Roles = "admin")]
        public ActionResult Delete(int id)
        {

           // Customer customer = this.repo.GetCustomerById(id);
            this.repo.DeleteCustomerById(id);
            return RedirectToAction("Manage");
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }
        
        [Authorize]
        public ActionResult Profile()
        {
            string name = User.Identity.Name;
            Customer c = this.repo.GetCustomerByName(name);
            if (c == null)
                return RedirectToAction("Logon", "Account"); 
            return View(c);
        }
        
        [Authorize(Roles = "admin")]
        public ActionResult Manage()
        {
            bool employee = false;
            if (Request.QueryString["employee"] != null)
            {
                employee = true;
            }
            ViewData["customers"] = this.repo.GetAllCustomers(employee);
            return View(ViewData);
        }

        [Authorize(Roles = "admin")]
        public ActionResult Edit(int id)
        {
            ViewDataCustomer customer= new ViewDataCustomer();
            customer = this.repo.GetCustomerById(id);
            return View(customer);
        }
          [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                ViewDataCustomer customer = new ViewDataCustomer();
                UpdateModel(customer);

                TempData["info"] = "Update resource successfully";
                return RedirectToAction("Edit", "Account", new { id = id });
            }
            catch
            {
                return View();
            }
        }
        [Authorize(Roles = "customer")]
        public ActionResult Checkout()
        {
            string name = User.Identity.Name;
            Customer c = this.repo.GetCustomerByName(name);
            if (c == null)
                return RedirectToAction("Logon", "Account");
            HttpCookie aCookie = Request.Cookies["Cart"];
            if (aCookie != null)
            {
               string t = aCookie.Value;
               t = Server.UrlDecode(t);
               string[] carts = t.Split(',');
               Order o = this.repo.CreateOrder(c.Id);

               int orderId = o.Id;
               for (int i = 0; i < carts.Length; i= i+6)
               {
                   OrderProduct op = new OrderProduct();
                   try
                   {
                        op.ProductId = Int32.Parse(carts[i]);
                        op.Quatity = Int32.Parse(carts[i+3]);
                        op.ProductType = Int32.Parse(carts[i + 1]);
                        op.OrderId = orderId;
                        op.ProductName = carts[i + 2];
                        op.Price = Int32.Parse(carts[i + 4]);
                        this.repo.CreateOrderProduct(op);
                   }
                   catch(Exception e)
                   {
                   }
               }
                aCookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(aCookie);
            }
            return RedirectToAction("Orders");
        }

        [Authorize(Roles = "customer")]
        public ActionResult Orders()
        {
            string name = User.Identity.Name;
            Customer c = this.repo.GetCustomerByName(name);
            ViewData["orders"] = this.repo.GetOrdersByCustomer(c.Id);
            return View(ViewData);
        }

        [Authorize(Roles = "admin")]
        public ActionResult Employees()
        {
            string name = User.Identity.Name;
            Customer c = this.repo.GetCustomerByName(name);
            ViewData["orders"] = this.repo.GetOrdersByCustomer(c.Id);
            return View(ViewData);
        }
        
        [Authorize]
        public ActionResult CustomIT()
        {
            string name = User.Identity.Name;
            Customer c = this.repo.GetCustomerByName(name);
            if (c == null)
            {
                TempData["info"] = "Error occured";
                return View();
            }
            int ActiveServer = this.repo.GetActiveServer(c.Id);
            int UsedCPU = this.repo.GetUsedCPU(c.Id);
            int UsedRAM = this.repo.GetUsedRAM(c.Id);
            int UsedStorage = this.repo.GetUsedStorage(c.Id);
            int PublicIP = this.repo.GetUsedPublicIP(c.Id);
            int Bandwith = this.repo.GetUsedBandwith(c.Id);
            ViewData["ActiveServer"] = ActiveServer;
            ViewData["UsedCPU"] = UsedCPU;
            ViewData["UsedRAM"] = UsedRAM;
            ViewData["UsedStorage"] = UsedStorage;
            ViewData["PublicIP"] = PublicIP;
            ViewData["Bandwith"] = Bandwith;
            return View(ViewData);
        }

    }
}
